<template>
  <div class="add-edit">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px">
      <div class="card-wrap info">
        <div class="add-edit-title">基本信息</div>
        <el-row>
          <el-col :span="11">
            <el-form-item label="展厅名称" prop="showroomName">
              <el-input v-model="ruleForm.showroomName" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="营业时间" prop="businessHoursInfo">
              <el-input v-model="ruleForm.businessHoursInfo" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="所在城市" prop="areaId">
              <div class="flex-row" style="width: 100%">
                <el-cascader
                  v-model="ruleForm.areaId"
                  :options="area"
                  :props="{
                    expandTrigger: 'hover',
                    value: 'cityCode',
                    label: 'name'
                  }"
                  style="width: 240px"
                />
                <el-form-item prop="areaDetailed" style="flex: 1">
                  <el-select
                    v-model="ruleForm.areaDetailed"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入详细地址"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    :disabled="!ruleForm.areaId || ruleForm.areaId.length == 0"
                  >
                    <el-option
                      v-for="item in areaDetailedOptions"
                      :key="item.location"
                      :label="item.name"
                      :value="item.location"
                    />
                  </el-select>
                </el-form-item>
              </div>

              <!-- <el-input v-model="ruleForm.businessHoursInfo" placeholder="请输入" clearable /> -->
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="地址补充说明" prop="areaSupplement">
              <el-input v-model="ruleForm.areaSupplement" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="展厅面积(㎡)" prop="proportion">
              <el-input-number
                v-model="ruleForm.proportion"
                :precision="2"
                :min="0"
                :controls="false"
                placeholder="请输入"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="商城最低折扣说明" prop="discount">
              <el-input v-model="ruleForm.discount" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="card-wrap">
        <div class="add-edit-title">可展示商品数量</div>
        <el-form-item label="可展示商品" prop="" required>
          <el-table class="table-wrap" :data="ruleForm.categoryList" stripe>
            <el-table-column label="商品" prop="categoryName" />
            <el-table-column label="可展示数量" width="400">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.productNum"
                  :precision="0"
                  :min="0"
                  :controls="false"
                  placeholder="请输入"
                  clearable
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
      <div class="card-wrap">
        <div class="add-edit-title">照片信息</div>
        <el-form-item label="展厅门头图" prop="headerResList">
          <AliOssUpload
            :fileList="ruleForm.headerResList"
            listType="picture-card"
            @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, 'headerResList')"
            :maxLength="10"
            :maxSize="5"
          >
            <template #tips>
              <div class="img-tips">单张不超过5M,支持jpeg，jpg，png格式</div>
            </template>
          </AliOssUpload>
        </el-form-item>
        <el-form-item label="展厅布局图" prop="layoutResList">
          <AliOssUpload
            :fileList="ruleForm.layoutResList"
            listType="picture-card"
            @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, 'layoutResList')"
            :maxLength="10"
            :maxSize="5"
          >
            <template #tips>
              <div class="img-tips">单张不超过5M,支持jpeg，jpg，png格式</div>
            </template>
          </AliOssUpload>
        </el-form-item>
        <el-form-item label="相册图片" prop="albumResList">
          <AliOssUpload
            :fileList="ruleForm.albumResList"
            listType="picture-card"
            @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, 'albumResList')"
            :maxLength="10"
            :maxSize="5"
            isImgTitle
          >
            <template #tips>
              <div class="img-tips">单张不超过5M,支持jpeg，jpg，png格式</div>
            </template>
          </AliOssUpload>
        </el-form-item>
        <el-form-item label="VR链接" prop="varPicList">
          <!-- <div class="flex-row flex-align"> -->
          <AliOssUpload
            :fileList="ruleForm.varPicList"
            listType="picture-card"
            @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, 'varPicList')"
            :maxLength="1"
            :maxSize="5"
          >
            <template #tips>
              <div class="img-tips">单张不超过5M,支持jpeg，jpg，png格式</div>
            </template>
          </AliOssUpload>
          <el-input v-model="ruleForm.vrUrl" placeholder="请输入VR链接" style="width: 300px; height: 30px" />
          <!-- </div> -->
        </el-form-item>
      </div>
    </el-form>

    <el-affix position="bottom" :offset="0">
      <div class="foot">
        <el-button class="btn" type="info" @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button class="btn" type="primary" @click="submitForm(ruleFormRef)"> 提交 </el-button>
      </div>
    </el-affix>
  </div>
</template>
<script setup>
import {
  createShowroom,
  inputtips,
  cpaShopCategoryDict,
  getShowroomDetail,
  modifyShowroom
} from "@/api/showRoomManagement/addEdit";
import { onMounted } from "vue";
import AliOssUpload from "@/components/AliOssUpload";
import { getArea } from "@/api/index.js";
import { ElMessage } from "element-plus";
const route = useRoute();
const router = useRouter();

const ruleFormRef = ref();
const ruleForm = ref({
  name: ""
});

const picIdLenValidator = (rule, value, callback) => {
  console.log(value);
  if (value && value.length > 0) {
    return callback();
  } else {
    return callback("请上传图片");
  }
};

const rules = reactive({
  showroomName: [{ required: true, message: "请输入展厅名称", trigger: "blur" }],
  businessHoursInfo: [{ required: true, message: "请输入营业时间", trigger: "blur" }],
  areaId: [{ required: true, message: "请选择所在城市", trigger: "change" }],
  areaDetailed: [{ required: true, message: "请输入详细地址", trigger: "change" }],
  proportion: [{ required: true, message: "请输入展厅面积(㎡)", trigger: "blur" }],
  discount: [{ required: true, message: "请输入商城最低折扣说明", trigger: "blur" }],
  headerResList: [{ required: true, validator: picIdLenValidator, trigger: "change" }],
  layoutResList: [{ required: true, validator: picIdLenValidator, trigger: "change" }],
  albumResList: [{ required: true, validator: picIdLenValidator, trigger: "change" }]
});

const areaDetailedOptions = ref([]);
const loading = ref(false);

// 远程搜索
const remoteMethod = query => {
  if (query) {
    loading.value = true;
    let queryData = {
      keywords: query,
      types: "",
      region: ruleForm.value.areaId[0],
      cityLimit: true
    };
    inputtips(queryData).then(res => {
      loading.value = false;
      areaDetailedOptions.value = res.data;
    });
  } else {
    areaDetailedOptions.value = [];
  }
};

// 商品分类
const cpaShopCategoryDictApi = async () => {
  await cpaShopCategoryDict().then(res => {
    ruleForm.value.categoryList = res.data;
  });
};

// 提交
const submitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      console.log(ruleForm.value);
      let params = JSON.parse(JSON.stringify(ruleForm.value));
      // 经纬度
      params.latitude = params.areaDetailed.split(",")[0];
      params.longitude = params.areaDetailed.split(",")[1];
      // 详细地址
      params.areaDetailed = areaDetailedOptions.value.find(item => {
        return item.location == ruleForm.value.areaDetailed;
      }).name;
      // 查询 城市层级、城市id、省市区名称
      treeSelect(area.value, ruleForm.value.areaId[0], params);
      // 重组图片数据
      params.headerResList = filerRecombination(params.headerResList);
      params.layoutResList = filerRecombination(params.layoutResList);
      params.albumResList = filerRecombination(params.albumResList);
      if (params.varPicList && params.varPicList.length > 0) {
        params.varPic = params.varPicList[0].fileUrl;
      }
      if (pageType.value == "add") {
        createShowroom(params).then(res => {
          ElMessage.success("添加成功");
          router.go(-1);
        });
      } else if (pageType.value == "edit") {
        modifyShowroom(params).then(res => {
          ElMessage.success("编辑成功");
          router.go(-1);
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 重组 false-提交时，true-详情回显时
const filerRecombination = (arr, isBoolean) => {
  if (arr && arr.length > 0) {
    let ObjArr = [];
    if (!isBoolean) {
      ObjArr = arr.map(item => {
        return {
          url: item.fileUrl,
          resourceId: item.fileId,
          title: item?.title
        };
      });
    } else if (isBoolean) {
      ObjArr = arr.map(item => {
        return {
          fileUrl: item.url,
          fileId: item.resourceId,
          title: item.title
        };
      });
    }
    return ObjArr;
  }
};

// 递归城市
const treeSelect = (arr, cityCode, params) => {
  const obj = arr.find(item => {
    return item.cityCode == cityCode;
  });
  if (obj.children) {
    treeSelect(obj.children, ruleForm.value.areaId[obj.level], params);
  } else {
    params.areaId = obj.id;
    params.areaAncestors = obj.ancestors;
    params.areaName = obj.sname;
  }
};

// 取消
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  router.go(-1);
};

const uploadSuccess = (file, fileList, key) => {
  ruleForm.value[key] = fileList;
};

// 城市选项列表
const area = ref([]);

// 详情
const getShowroomDetailApi = () => {
  getShowroomDetail({ showroomId: route.query.showroomId }).then(res => {
    ruleForm.value = res.data;
    ruleForm.value.areaId = res.data.areaAncestors.split(",");
    if (res.data.varPic) {
      ruleForm.value.varPicList = [
        {
          fileUrl: res.data.varPic
        }
      ];
    }
    ruleForm.value.headerResList = filerRecombination(ruleForm.value.headerResList, true);
    ruleForm.value.layoutResList = filerRecombination(ruleForm.value.layoutResList, true);
    ruleForm.value.albumResList = filerRecombination(ruleForm.value.albumResList, true);
    areaDetailedOptions.value = [
      {
        name: ruleForm.value.areaDetailed,
        location: ruleForm.value.latitude + "," + ruleForm.value.longitude
      }
    ];
    ruleForm.value.areaDetailed = ruleForm.value.latitude + "," + ruleForm.value.longitude;
  });
};

// 页面类型-新增、修改
const pageType = ref("add");

onMounted(async () => {
  await cpaShopCategoryDictApi();
  getArea().then(res => {
    area.value = res.data;
  });
  // 如果有值-则编辑
  if (route.query.showroomId) {
    getShowroomDetailApi();
    pageType.value = "edit";
  } else {
    pageType.value = "add";
  }
});
</script>
<style scoped lang="scss">
.add-edit {
  background: #f5f7fa;
  border-radius: 10px;
  overflow: hidden;
  .card-wrap {
    padding: 36px 70px 32px 22px;
    background-color: #fff;
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    .add-edit-title {
      font-size: 18px;
      color: #131414;
      margin-bottom: 28px;
    }
    .upload-img {
      ::v-deep(.el-upload-list__item) {
        width: 100px;
        height: 100px;
      }
      ::v-deep(.el-upload) {
        width: 100px;
        height: 100px;
      }
    }
    .img-tips {
      font-size: 12px;
      color: #86909c;
    }
  }
  .info {
    padding-top: 24px;
  }

  .foot {
    background: #ffffff;
    box-shadow: 0px -5px 10px 0px rgba(66, 78, 102, 0.15);
    padding: 15px 20px;
    text-align: right;
    // width: calc(100% - 40px);
    .radio {
      ::v-deep(.is-checked) {
        .el-radio__label {
          color: #606266;
        }
      }
    }
    .btn {
      width: 120px;
      height: 36px;
    }
  }
  .agreement-dialog {
    .info {
      height: 595px;
      background: #ecf0f4;
      overflow-y: scroll;
      padding: 20px 30px;
    }
    .btn {
      width: 180px;
    }
  }
}
</style>
